﻿using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Animation;
using CommunityToolkit.Mvvm.DependencyInjection;
using FanaticRock.AudioManage.Helpers;
using FanaticRock.Core.DI;
using FanaticRock.Core.Helpers;
using FanaticRock.Core.Models;
using FanaticRock.Core.ServiceInterfaces;
using FanaticRock.Events;
using FanaticRock.Helpers;
using FanaticRock.Theme.Utils;
using FanaticRock.ViewModels;
using LiteDB;

namespace FanaticRock.Views
{
    /// <summary>
    /// ShellWindow.xaml 的交互逻辑
    /// </summary>
    [InjectMe]
    public partial class ShellWindow : Window
    {
        #region fields

        private bool _isMusicPanelExpand = false;
        private bool _isRightDockPlayListExpand = false;

        #endregion

        #region ctors

        public ShellWindow(MainViewModel dataContext)
        {
            InitializeComponent();

            DataContext = dataContext;
            SizeChanged += ShellWindow_SizeChanged;
            AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnButtonClicked));
        }

        #endregion

        #region events impls
        private void OnButtonClicked(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is ButtonBase button)
            {
                var tag = button.Tag as string;
                if (string.IsNullOrWhiteSpace(tag)) return;
                if (string.Equals(tag, "fold_music_panel"))
                {
                    SetMusicPanelExpand(false);
                }
                else if (string.Equals(tag, "expand_music_panel"))
                {
                    SetMusicPanelExpand(true);
                }
                else if (string.Equals(tag, "close_right_dock_play_list_view"))
                {
                    SetRightDockPlayListExpand(false);
                }
                else if (string.Equals(tag, "open_right_dock_play_list_view"))
                {
                    SetRightDockPlayListExpand(true);
                }
                else if (string.Equals(tag, "close_window"))
                {
                    CloseWindow();
                }
                else if (string.Equals(tag, "min_window"))
                {
                    WindowState = WindowState.Minimized;
                }
                else if (string.Equals(tag, "resize_window"))
                {
                    if (WindowState == WindowState.Maximized)
                        WindowState = WindowState.Normal;
                    else
                        WindowState = WindowState.Maximized;
                }
                else if (string.Equals(tag, "open_bilibili"))
                {
                    WindowHelper.Show<BilibiliShell.Views.ShellView>();
                }
                else if (string.Equals(tag, "goto_previous_page"))
                {
                    var extendNavigationService = GetExtendNavigationService();
                    extendNavigationService.NavigateBack();
                }
                else if (string.Equals(tag, "goto_next_page"))
                {
                    //var extendNavigationService = GetExtendNavigationService();
                    //extendNavigationService.NavigateForward();
                }
                else if (string.Equals(tag, "option_setting_config"))
                {
                    var extendNavigationService = GetExtendNavigationService();
                    extendNavigationService.Navigate(new Uri(@"pack://application:,,,/FanaticRock;component/Views/Main/Pages/OptionSettingConfigView.xaml") ,null);
                }
            }
        }

        private void ShellWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {

            SetMusicPanelExpand(_isMusicPanelExpand, ActualHeight);

        }

        #endregion


        #region methods

        // 获得导航服务。
        private ExtendNavigationService GetExtendNavigationService()
        {
            return ExtendNavigationServices.GetExtendNavigationService(PART_MainHostView.PART_Frame.NavigationService);
        }

        // 处理消息通知。
        internal void ReceiveMessage(AppMessageEventArgs message)
        {
            PART_NoticeCardHost.Notice(message.NoticeType, message.Title, message.Content);
        }

        // 关闭窗口。
        private void CloseWindow()
        {
            Close();
        }


        private void SetMusicPanelExpand(bool value)
        {
            SetMusicPanelExpand(value, ActualHeight);
        }

        private void SetMusicPanelExpand(bool value, double winHeight)
        {
            _isMusicPanelExpand = value;
            var musicPanelMargin = new Thickness(0);
            if (value == false)
            {
                musicPanelMargin = new Thickness(0, winHeight, 0, 0);
            }
            else
            {
                PART_MusicHostView.Visibility = Visibility.Visible;
            }

            var duration = new Duration(TimeSpan.FromMilliseconds(400));
            var marginAnimation = new ThicknessAnimation(musicPanelMargin, duration);
            marginAnimation.EasingFunction = new QuinticEase() { EasingMode = EasingMode.EaseOut };
            PART_MusicHostView.BeginAnimation(MarginProperty, marginAnimation, HandoffBehavior.SnapshotAndReplace);
        }

        private void SetMusicPanelExpandNoAnimation(bool value, double winHeight)
        {
            _isMusicPanelExpand = value;
            var musicPanelMargin = new Thickness(0);
            if (value == true)
            {
                musicPanelMargin = new Thickness(0, -winHeight, 0, 0);
            }
            PART_MusicHostView.Margin = musicPanelMargin;
        }

        private void SetRightDockPlayListExpand(bool value)
        {
            var transform = PART_RightDockPlayListView.RenderTransform as TranslateTransform;
            if (transform == null) throw new Exception("ShellWindow.SetRightDockPlayListExpand: 控件 SetRightDockPlayListExpand 的 RenderTransform 请注意只有一个 TranslateTransform，没有别的什么 TransformGroup");

            _isRightDockPlayListExpand = value;
            var rightDockListViewXOffset = PART_RightDockPlayListView.Width;

            // 当变为 true 是表示展开
            if (value == true)
            {
                rightDockListViewXOffset = 0;
                PART_ContainerGrid.IsHitTestVisible = false;
                PART_RightDockPlayListView.IsHitTestVisible = true;
                PART_MaskGrid.Visibility = Visibility.Visible;
            }
            else
            {
                PART_ContainerGrid.IsHitTestVisible = true;
                PART_RightDockPlayListView.IsHitTestVisible = false;
                PART_MaskGrid.Visibility = Visibility.Hidden;
            }

            var duration = new Duration(TimeSpan.FromMilliseconds(500));

            var xAnimation = new DoubleAnimation(rightDockListViewXOffset, duration);
            xAnimation.EasingFunction = new QuinticEase() { EasingMode = EasingMode.EaseOut };
            transform.BeginAnimation(TranslateTransform.XProperty, xAnimation, HandoffBehavior.SnapshotAndReplace);
        }


        #endregion

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var localDbService = Ioc.Default.GetService<ILocalDbService>();
            var songs = await localDbService.Query<FanaticRock.AudioManage.Models.SongInPlayList>();

            foreach (var song in songs)
            {
                var uri = song.Uri;
                var localPath = uri.LocalPath;
                var coverPath = Path.Combine(Path.GetDirectoryName(localPath), "cover.png");

                song.CoverSource = new UriResourceSource(UriHelper.GetLocalUri(coverPath));

                //var bytes = AudioFormatHelper.TryGetCover(localPath);
                //File.WriteAllBytes(coverPath, bytes);

            }

            await localDbService.Clear<FanaticRock.AudioManage.Models.SongInPlayList>();
            await localDbService.UpsertAsync<FanaticRock.AudioManage.Models.SongInPlayList>(songs);
        }
    }

}
